﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using YiSha.Admin.Web.Controllers;
using YiSha.Business.OrganizationManage;
using YiSha.Business.Test;
using YiSha.Entity.OrganizationManage;
using YiSha.Entity.Test;
using YiSha.Model.Param.Test;
using YiSha.Model.Result.PMCManage;
using YiSha.Util.Extension;
using YiSha.Util.Model;
using YiSha.Web.Code;

namespace YiSha.Admin.Web.Areas.PMCManage.Controllers
{
    [Area("PMCManage")]
    public class ScheduleController : BaseController
    {

        private readonly ScheduleBLL scheduleBLL = new ScheduleBLL();

        private readonly DepartmentBLL departmentBLL = new DepartmentBLL();

        private readonly ProcessBLL processBLL = new ProcessBLL();

        #region 视图功能
        [AuthorizeFilter("pmc:schedule:addView")]
        public IActionResult ScheduleAddIndex()
        {
            return View();
        }

        [AuthorizeFilter("pmc:schedule:panel")]//排产面板
        public IActionResult SchedulePanel()
        {
            return View();
        }

        [AuthorizeFilter("pmc:schedule:track")]//排产跟踪
        public IActionResult ScheduleTrack()
        {
            return View();
        }
        #endregion

        #region 获取数据接口
        [HttpPost]
        [AuthorizeFilter("pmc:schedule:addView")]//获取工单
        public async Task<IActionResult> GetListJson([FromBody] ScheduleParam param)//获取某一工令号对应的工单
        {
            ScheduleParam scheduleParam = new ScheduleParam
            {
                WorkOrderNumber = param.WorkOrderNumber
            };
            List<ScheduleEntity> obj = await scheduleBLL.GetListJson(scheduleParam);
            return Json(obj);
        }

        [HttpPost]
        [AuthorizeFilter("pmc:schedule:addView")]
        //获取该工令各个工序的实际完成数量（该方法可能暂时不用）
        public async Task<IActionResult> GetProcessCompletedQuantities([FromBody] GetPlanDataParam param)//根据工令号与工序Id计算
        {

            var result = new List<object>();

            ScheduleParam scheduleParam = new ScheduleParam
            {
                WorkOrderNumber = param.WorkOrderNumber
            };

            foreach (long processId in param.ProcessIds)
            {
                scheduleParam.ProcessId = processId;
                List<ScheduleEntity> obj = await scheduleBLL.GetListJson(scheduleParam);
                int? total = 0;
                foreach (var item in obj)
                {
                    if (item.RealNumber != -1)
                    {
                        total += item.RealNumber;
                    }
                }
                result.Add(new
                {
                    processId,
                    completedQuantity = total
                });
            }

            return Json(result);
        }

        [HttpPost]
        [AuthorizeFilter("pmc:schedule:addView")]
        public async Task<IActionResult> GetPlanData([FromBody] GetPlanDataParam param)//根据工令号、工序id数组、开始日期与日期长度获取计划产量
        {
            // 验证参数
            if (param == null || string.IsNullOrEmpty(param.WorkOrderNumber) ||
                param.ProcessIds == null || param.ProcessIds.Length == 0)
            {
                return Json(new List<ScheduleEntity>());
            }

            // 生成日期范围
            List<DateTime> dateRange = new List<DateTime>();
            for (int i = 0; i < param.Length; i++)
            {
                dateRange.Add(param.StartDate.Date.AddDays(i));
            }

            // 构建查询条件并执行查询
            ScheduleParam scheduleParam = new ScheduleParam
            {
                WorkOrderNumber = param.WorkOrderNumber
            };

            List<ScheduleEntity> result = new List<ScheduleEntity>();

            foreach (long processId in param.ProcessIds)
            {
                foreach (DateTime date in dateRange)
                {
                    scheduleParam.ProcessId = processId;
                    scheduleParam.Date = date;

                    List<ScheduleEntity> data = await scheduleBLL.GetListJson(scheduleParam);
                    if (data != null && data.Count > 0)
                    {
                        result.AddRange(data);
                    }
                }
            }

            return Json(result);
        }

        [HttpPost]
        [AuthorizeFilter("pmc:schedule:panel")]//获取日报面板数据
        public async Task<IActionResult> GetDayPanel([FromForm] ScheduleParam param)//根据其内的具体某一天日期获取日报数量
        {

            // 验证日期参数是否为空
            if (!param.Date.HasValue)
            {
                return Json(new TData<string>
                {
                    Tag = 0,
                    Message = "日期参数不能为空，请选择要查询的日期",
                    Data = null
                });
            }

            //根据用户所在部门判断其能查看的工序有哪些
            OperatorInfo user = await Operator.Instance.Current();
            // 验证部门Id是否为空
            if (!user.DepartmentId.HasValue)
            {
                return Json(new TData<string>
                {
                    Tag = 0,
                    Message = "部门不能为空，请联系管理员为你划分部门",
                    Data = null
                });
            }
            long departmentId = (long)user.DepartmentId;//获取当前用户部门Id
            TData<DepartmentEntity> departmentEntity = await departmentBLL.GetEntity(departmentId);//根据部门id查出所属部门

            //后期需要根据工令状态查询特定的工令，避免全查操作。

            try
            {
                // 调用业务逻辑层获取日报面板数据
                List<WorkOrderNumberDayInfo> result = await scheduleBLL.GetDayPanel(param.Date.Value, departmentEntity.Data.Remark);
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(new TData<string>
                {
                    Tag = 0,
                    Message = "获取日报面板数据失败：" + ex.Message,
                    Data = null
                });
            }
        }
        #endregion

        #region 提交数据接口
        [HttpPost]
        [AuthorizeFilter("pmc:schedule:addView")]//新增的视图需要有修改的功能
        public async Task<IActionResult> InsertOrUpdateScheduleAsync([FromBody] List<ScheduleEntity> data)
        {
            OperatorInfo user = await Operator.Instance.Current();
            // 获取当前中国标准时间
            DateTime chinaTime = DateTime.Now;
            ScheduleParam scheduleParam = new ScheduleParam();
            foreach (var item in data)
            {
                scheduleParam.WorkOrderNumber = item.WorkOrderNumber;
                scheduleParam.ProcessId = item.ProcessId;
                scheduleParam.Date = item.Date;
                List<ScheduleEntity> scheduleData = await scheduleBLL.GetListJson(scheduleParam);
                if (scheduleData == null || scheduleData.Count == 0)//为空表示新增
                {
                    item.BaseCreateTime = chinaTime;
                    item.BaseCreatorId = user.UserId;
                    _ = scheduleBLL.Insert(item);
                }
                else if (scheduleData.Count == 1)//长度为1表示更新
                {
                    scheduleData[0].BaseModifyTime = chinaTime;
                    scheduleData[0].BaseModifierId = user.UserId;
                    if (scheduleData[0].PlanNumber != item.PlanNumber)//计划产量有更新时
                    {
                        scheduleData[0].PlanNumber = item.PlanNumber;
                        _ = scheduleBLL.Update(scheduleData[0]);
                    }
                }
                else//其他都是异常情况
                {
                    //回滚操作待完善
                    return Json(new { success = false, message = "发生异常，数据已回滚（回滚待实现）", dataCount = data?.Count ?? 0 });
                }
            }
            return Json(new { success = true, message = "数据接收成功", dataCount = data?.Count ?? 0 });
        }
        #endregion

    }

    /// <summary>
    /// 获取计划数据的参数模型
    /// </summary>
    public class GetPlanDataParam
    {
        /// <summary>
        /// 工令号
        /// </summary>
        public string WorkOrderNumber { get; set; }

        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime StartDate { get; set; }

        /// <summary>
        /// 日期长度
        /// </summary>
        public int Length { get; set; } = 7;

        /// <summary>
        /// 工序ID数组
        /// </summary>
        public long[] ProcessIds { get; set; }
    }
}
